<?php
/**
 * Notes:发送短信
 * author: chen
 * DateTime: 2022/3/1 16:29
 * @package Xtsb\Cims\AliCloudSMS
 */

namespace Xtsb\Cims\AliCloudSMS;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class AliCloud
{
  /**
   * 使用AK&SK初始化账号Client
   * @param string $accessKeyId
   * @param string $accessKeySecret
   * @return Dysmsapi Client
   */
  public static function createClient($accessKeyId, $accessKeySecret)
  {
    $config = new Config([
      // 您的AccessKey ID
      "accessKeyId" => $accessKeyId,
      // 您的AccessKey Secret
      "accessKeySecret" => $accessKeySecret
    ]);
    // 访问的域名
    $config->endpoint = "dysmsapi.aliyuncs.com";
    return new Dysmsapi($config);
  }

  /**
   * Notes:
   * author: chen
   * DateTime: 2022/3/1 16:46
   * @param $phone
   * @param $params array 参数数组
   * @param $merchantSmsConfigInfo
   * @return void
   */
  public static function main($phone, $templateCode, $params = null)
  {
    $client = self::createClient("LTAIWtAcYT23RQJC", "x2AeeCAAh3OTuAXHTUBwlcK0fKibo4");
    $SendSmsRequest = [
      "phoneNumbers" => $phone,
      "signName" => "信钛速保",
      "templateCode" => $templateCode,//模板
    ];

    //验证码
    if (isset($params['code'])) {
      $SendSmsRequest['templateParam'] = "{\"code\":{$params['code']}}";
    }//
    //充值
    else if (isset($params['name']) && isset($params['fee'])) {
      $SendSmsRequest['templateParam'] = "{\"name\":\"{$params['name']}\",\"fee\":\"人民币 {$params['fee']}元\"}";
    }//
    //企业账号过期提示
    else if (isset($params)) {
      $SendSmsRequest['templateParam'] = json_encode($params, JSON_UNESCAPED_UNICODE);
    }

    $sendSmsRequest = new SendSmsRequest($SendSmsRequest);
    // 复制代码运行请自行打印 API 的返回值
    $result = $client->sendSms($sendSmsRequest);


    return $result;
  }


  public static function sendSms($phone, $templateCode, $params = null)
  {
    $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
    if (file_exists($path)) {
      require_once $path;
    }
    return Self::main($phone, $templateCode, $params);
  }
}


